/*
 * Copyright by Pietro Lusso 2014
 */

// Draw and modify
var FMap = {};

var areas = [];
var featureOverlay;
var modify;
var draw = null; // global so we can remove it later

FMap.startDraw = function(map, color) {

	// Toggle draw mode
	if (draw != null) {
		map.removeInteraction(draw);
		draw = null;
		return;
	}

	featureOverlay = new ol.FeatureOverlay({
		style : new ol.style.Style({
			fill : new ol.style.Fill({
				color : color
			}),
			stroke : new ol.style.Stroke({
				color : '#aa0000',
				width : 2
			}),
			image : new ol.style.Circle({
				radius : 7,
				fill : new ol.style.Fill({
					color : '#ffcc33'
				})
			})
		})
	});
	featureOverlay.setMap(map);

	// Now you can set other data for the area, for example if it's a territory,
	// or simply a custom area and city name and so on
	featureOverlay.number = "100";
	featureOverlay.city = "Sielmingen";

	modify = new ol.interaction.Modify({
		features : featureOverlay.getFeatures(),
		// the SHIFT key must be pressed to delete vertices, so
		// that new vertices can be drawn at the same position
		// of existing vertices
		deleteCondition : function(event) {
			return ol.events.condition.shiftKeyOnly(event)
					&& ol.events.condition.singleClick(event);
		}
	});
	map.addInteraction(modify);

	function addInteraction() {
		draw = new ol.interaction.Draw({
			features : featureOverlay.getFeatures(),
			type : "Polygon",
			drawend : function() {
			}
		});
		map.addInteraction(this.draw);
	}

	addInteraction();

	// Callback function which needs to be overwritten
	draw.on('drawend', function(e) { FMap.drawEndCallbackFunction(e); });
};

FMap.drawEndCallbackFunction = function(e) {
	console.log("You need to overwrite this function first!");
};

// Insert Territories from Text
var insertedTerritories = [];

FMap.insertFeaturesFromText = function(text, color) {

	var IMPORTER = new ol.format.WKT();

	var importedFeatureOverlay = new ol.FeatureOverlay({
		style : new ol.style.Style({
			fill : new ol.style.Fill({
				color : color
			}),
			stroke : new ol.style.Stroke({
				color : color,
				width : 4
			}),
			image : new ol.style.Circle({
				radius : 7,
				fill : new ol.style.Fill({
					color : color
				})
			})
		})
	});

	importedFeatureOverlay.setMap(map);
	importedFeatureOverlay.addFeature(IMPORTER.readFeature(text));
	insertedTerritories.push(importedFeatureOverlay);
};

FMap.clearInsertedFeatures = function() {
	insertedTerritories.forEach(function(featureOverlay) {
		featureOverlay.getFeatures().clear();
	});
};